package cn.yuanqiao.archive.Identify.service.impl;/**
 * @author 赵常飞
 * @date 2023/7/10 10:25
 */


import cn.yuanqiao.activiti.domain.ActivitiPackage;
import cn.yuanqiao.activiti.service.RemoteActivitiService;
import cn.yuanqiao.archive.Identify.domain.YqMjApprove;
import cn.yuanqiao.archive.Identify.mapper.MjIdentifyMapper;
import cn.yuanqiao.archive.Identify.mapper.YqMjApproveMapper;
import cn.yuanqiao.archive.Identify.service.IMjIdentifyService;
import cn.yuanqiao.archive.appManager.domain.DataScopeBase;
import cn.yuanqiao.archive.appManager.domain.TenantApply;
import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.mapper.TenantApplyMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.enums.DbIdEnum;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.PageUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.yuanqiao.common.config.YqDatabaseIdProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @AUTHOR:赵常飞
 * @date 2023/7/10 10:25
 */
@Service
public class MjIdentifyServiceImpl implements IMjIdentifyService {
    @Autowired
    private TenantApplyMapper tenantApplyMapper;

    @Autowired
    private TenantCategoryMapper tenantCategoryMapper;

    @Autowired
    private MjIdentifyMapper mjIdentifyMapper;

    @Autowired
    private RemoteActivitiService remoteActivitiService;

    @Autowired
    private YqMjApproveMapper yqMjApproveMapper;
    @Autowired
    private YqDatabaseIdProvider yqDatabaseIdProvider;

    private String dataBaseId;

    @PostConstruct
    public void getDatabaseId() {
        dataBaseId =  yqDatabaseIdProvider.getDatabaseId();
    }
    /**
     * 列表查询接口
     *
     * @param
     * @return
     */
    @Override
    public List<Map<String, Object>> getlist(JSONObject json, String approveType) {
        String categoryId = json.getString("categoryId"); //门类id
        String menuId = json.getString("menuId"); //菜单id
        String type = json.getString("type"); //0 件 1 卷  3 项目
        String fields = json.getString("fields"); //需要查询字段
        JSONArray propertyName = json.getJSONArray("propertyName");//分类节点的属性
        JSONArray propertyValue = json.getJSONArray("propertyValue");//分类节点的值
        JSONArray jsonArray = json.getJSONArray("searchcolumn");//查询条件
        //获取当前登录用户信息
        String tenantCode = SecurityUtils.getTenantCode();
        /**处理表名*/
        TenantCategory category = new TenantCategory();
        //查询门类信息
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId), category.getTableName());
        //应用定义表名处理
        TenantApply tenantApply = new TenantApply();
        //查询应用定义信息
        TenantApply tenantApplyQuery = tenantApplyMapper.selectYqdaApplyModelById(Long.valueOf(menuId), Long.valueOf(categoryId), tenantApply.getTableName());
        String tableName = "";
        String order = "";
        String daFolderTable = "";
        //组件信息
        if (type.equals("0")) {
            tableName = tenantCategory.getFileTableName();
            if (tenantApplyQuery != null) {
                order = handlSeqencing(tenantApplyQuery.getJianorder(), " ff.");
            }
            if (tenantCategory.getType() != 0) {
                daFolderTable = tenantCode + Constants.BIG_TABLE_FOLDER_NAME;
            }
        }
        //组卷
        if (type.equals("1")) {
            tableName = tenantCategory.getFolderTableName();
            if (tenantApplyQuery != null) {
                order = handlSeqencing(tenantApplyQuery.getJuanorder(), " ff.");
            }
        }
        //项目
        if (type.equals("3")) {
            tableName = tenantCategory.getItemTableName();
            if (tenantApplyQuery != null) {
                order = handlSeqencing(tenantApplyQuery.getXiangmuorder(), " ff.");
            }
        }
        if (!StringUtils.isEmpty(json.getString("order"))){
            if ("".equals(order)){
                order += " order by ff."+json.getString("order");
            }else {
                order += " ,ff."+json.getString("order");
            }
        }
        StringBuilder tiaojian = new StringBuilder(" and ");
        /**处理查询条件*/
        if (null == jsonArray) {
            jsonArray = new JSONArray();
        }
        if (jsonArray.size() > 0) {
            concatQueryCondition(jsonArray, tiaojian, " ff.");
        }
        /**处理分类值*/
        if (propertyName.size() > 0) {
            for (int i = 0; i < propertyName.size(); i++) {
                tiaojian.append(" ff." + propertyName.get(i) + " = " + "'" + propertyValue.get(i) + "' and ");
            }
        }
        String tiaojianQuery = tiaojian.toString();
        /**处理拼接条件时的sql*/
        if (tiaojianQuery.endsWith("and ")) {
            tiaojianQuery = tiaojianQuery.substring(0, tiaojian.length() - 4);
        } else if (tiaojianQuery.endsWith("and")) {
            tiaojianQuery = tiaojianQuery.substring(0, tiaojian.length() - 3);
        }
        //拼接id
        StringBuilder field = new StringBuilder();
        String[] fieldArr = fields.split(",");
        for (String f : fieldArr) {
            field.append(" ff." + f + ",");
        }
        field.append(" ff.ID ");
        //查询件的信息
        PageUtils.startPage();
        if ("2".equals(approveType)) {
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String nowdate = sdf.format(date);
            String bgqxgqsql = "";
            if (dataBaseId.equalsIgnoreCase(DbIdEnum.OSCAR.getCode())) {
                bgqxgqsql = " AND ( ff.id IN (SELECT id FROM (SELECT id, replace(bgqx, 'D', '') " +
                        " AS bgqxnum, bgqx, rq, jdsj, to_char(to_date((CASE WHEN jdsj IS NULL THEN (CASE WHEN rq is not null " +
                        " THEN rq ELSE '19000101' END) ELSE jdsj END), case when locate('-',(CASE WHEN jdsj IS NULL THEN (CASE WHEN rq IS NOT NULL THEN rq ELSE '19000101' END ) ELSE jdsj END))!=0 then 'YYYY-MM-DD' else 'YYYYMMDD' END),'YYYYMMDD') AS formatrq, to_char((to_date((CASE WHEN jdsj " +
                        " IS NULL THEN (CASE WHEN rq is not null THEN rq ELSE '19000101' END) ELSE jdsj END), case when locate('-',(CASE WHEN jdsj IS NULL THEN (CASE WHEN rq IS NOT NULL THEN rq ELSE '19000101' END ) ELSE jdsj END))!=0 then 'YYYY-MM-DD' else 'YYYYMMDD' END) + replace(bgqx, 'D', '') * 365),'YYYYMMDD')" +
                        " AS gqsj FROM " + tableName + " ) WHERE gqsj <= '" + nowdate + "')) AND bgqx not in ('Y','DQ','CQ') ";
            } else if (dataBaseId.equalsIgnoreCase(DbIdEnum.HIGHGO.getCode()) || dataBaseId.equalsIgnoreCase(DbIdEnum.KINGBASE.getCode())) {
                bgqxgqsql = " AND ( ff.id IN (SELECT id FROM (SELECT id, replace(bgqx, 'D', '') " +
                        " AS bgqxnum, bgqx, rq, jdsj, to_date((CASE WHEN jdsj IS NULL THEN (CASE WHEN (rq is null) " +
                        " THEN rq ELSE '19000101' END) ELSE jdsj END), 'YYYYMMDD')  AS formatrq, (to_date((CASE WHEN jdsj " +
                        " IS NULL THEN (CASE WHEN (rq is null) THEN rq ELSE '19000101' END) ELSE jdsj END), 'YYYYMMDD') + replace(bgqx, 'D', '') * 365)" +
                        " AS gqsj FROM " + tableName + " WHERE bgqx not in ('Y','DQ','CQ') ) WHERE gqsj <= '" + nowdate + "')) ";
            } else {
                bgqxgqsql = " AND ( ff.id IN (SELECT id FROM (SELECT id, replace(bgqx, 'D', '') " +
                        " AS bgqxnum, bgqx, rq, jdsj, DATE_FORMAT((CASE WHEN jdsj IS NULL THEN (CASE WHEN (isdate(rq)) = 1 " +
                        " THEN rq ELSE '19000101' END) ELSE jdsj END), 'YYYYMMDD')  AS formatrq, (DATE_FORMAT((CASE WHEN jdsj " +
                        " IS NULL THEN (CASE WHEN (isdate(rq)) = 1 THEN rq ELSE '19000101' END) ELSE jdsj END), 'YYYYMMDD') + replace(bgqx, 'D', '') * 365)" +
                        " AS gqsj FROM " + tableName + " WHERE bgqx not in ('Y','DQ','CQ')) WHERE gqsj <= '" + nowdate + "')) ";
            }
            tiaojianQuery = tiaojianQuery + bgqxgqsql;
        }
        List<Map<String, Object>> mapList = mjIdentifyMapper.getlist(new DataScopeBase(Long.valueOf(menuId)), field.toString(), tableName, daFolderTable, new YqMjApprove().getTableName(), tiaojianQuery, order, approveType);
        return mapList;
    }


    /**
     * 审核通过后修改密级
     *
     * @return
     */
    @Transactional
    @Override
    public int updateMjType(String id) {
        YqMjApprove yqMjApprove = yqMjApproveMapper.selectYqMjApproveByID(id, new YqMjApprove().getTableName());
        //todo  通过审批 修改档案信息密级状态  并更新关联表信息
        updateData(yqMjApprove.getFilesId(), yqMjApprove.getCategoryId(), yqMjApprove.getType(), yqMjApprove.getMjType());
        yqMjApprove.setState("2");
        yqMjApprove.setTask("1");
        yqMjApproveMapper.updateYqMjApprove(yqMjApprove, new YqMjApprove().getTableName());
        return 1;
    }

    /**
     * 审批未通过
     *
     * @param id
     * @return
     */
    @Override
    public int disagreeMjType(String id) {
        YqMjApprove yqMjApproveDate = yqMjApproveMapper.selectYqMjApproveByID(id, new YqMjApprove().getTableName());
        StringBuilder sql = new StringBuilder("");
        sql.append(" select  IFNULL( MJ,'-1') AS MJ from " + yqMjApproveDate.getSubTableName());
        sql.append(" where ID = " + yqMjApproveDate.getFilesId());
        List<Map<String, Object>> mapList = mjIdentifyMapper.selectUnionALLTableData("t.MJ", sql.toString());
        String mj = mapList.get(0).get("MJ").toString();
        //todo  审批退回后 修改档案信息密级状态  并更新关联表信息
        YqMjApprove yqMjApprove = new YqMjApprove();
        yqMjApprove.setId(id);
        yqMjApprove.setState("2");
        yqMjApprove.setMjType(mj);
        yqMjApprove.setTask("0");
        yqMjApproveMapper.updateYqMjApprove(yqMjApprove, yqMjApprove.getTableName());
        return 1;
    }


    /**
     * 调整密级接口  先新增到密级审批表里
     *
     * @param yqMjApprove
     * @return
     */
    @Override
    public int insMjType(List<YqMjApprove> yqMjApprove) {
        yqMjApprove.stream().forEach(l -> {
            Integer type = Integer.parseInt(l.getType());
            int max = determineMjType(l);
            if (max != -1) {
                //件
                if (type == 0) {
                    if (Integer.parseInt(l.getMjType()) > max) {
                        throw new ServiceException("卷内件密级不能大于卷的密级");
                    }
                }
                //组卷
                if (type == 1) {
                    if (Integer.parseInt(l.getMjType()) < max) {
                        throw new ServiceException("卷内件密级不能大于卷的密级");
                    }
                }
            }
            l.setId(String.valueOf(SnowflakeIdGenerator.generateId()));
            l.setCreateTime(new Date());
            l.setCreatorId(String.valueOf(SecurityUtils.getUserId()));
            l.setCreator(SecurityUtils.getUsername());
            l.setApproveType("1");
//            Map<String, Object> variables = new HashMap<>();
//           // variables.put("processVariables", l.toProcessMap());
//            variables.put("identifyId", l.getID());
//            variables.put("archiveData", yqMjApprove);
//            R<ActivitiPackage> activitiPackageR = remoteActivitiService.startProcessWsArchiveMJIdentify(variables);
//            l.setProcessInstance(activitiPackageR.getData().getProcessInstance().getProcessInstanceId());
//            //l.setTask(activitiPackageR.getData().getTask().getId());
//            l.setState("1");
//            yqMjApproveMapper.insertYqMjApprove(l, new YqMjApprove().getTableName());
        });
        yqMjApprove.stream().forEach(l -> {
            Map<String, Object> variables = new HashMap<>();
            // variables.put("processVariables", l.toProcessMap());
            variables.put("identifyId", l.getId());
            variables.put("archiveData", Stream.of(l.toProcessMap()).collect(Collectors.toList()));
            R<ActivitiPackage> activitiPackageR = remoteActivitiService.startProcessWsArchiveMJIdentify(variables);
            l.setProcessInstance(activitiPackageR.getData().getProcessInstance().getProcessInstanceId());
            l.setState("1");
            yqMjApproveMapper.insertYqMjApprove(l, new YqMjApprove().getTableName());
        });
        return 1;
    }

    /**
     * 取消审批
     *
     * @param
     * @return
     */
    @Override
    public int cancelApproval(String id) {
        //先查审批表数据 判断是否可以取消审批
        YqMjApprove yqMjApprove = yqMjApproveMapper.selectYqMjApproveByID(id, new YqMjApprove().getTableName());
        return yqMjApproveMapper.updateYqMjApproveState(id, new YqMjApprove().getTableName());
    }

    /**
     * 查询审批详情
     *
     * @param
     * @return
     */
    @Override
    public YqMjApprove initiateApproval(String id) {
        //先查审批表数据 判断是否可以取消审批
        YqMjApprove yqMjApprove = yqMjApproveMapper.selectYqMjApproveByID(id, new YqMjApprove().getTableName());
        R<List<ActivitiPackage>> taskByInstanceId = remoteActivitiService.getTaskByInstanceId(yqMjApprove.getProcessInstance());
        String assigned = taskByInstanceId.getData().stream().filter(f -> f.getTask().getStatus().name().equals("ASSIGNED")).map(m -> m.getTask().getId()).collect(Collectors.joining());
        yqMjApprove.setTaskId(assigned);
        return yqMjApprove;
    }

    /**
     * 查询密级审批列表
     *
     * @param yqMjApprove
     * @return
     */
    @Override
    public List<YqMjApprove> YqMjApproveList(YqMjApprove yqMjApprove) {
        yqMjApprove.setApproveType("1");
        return yqMjApproveMapper.selectYqMjApproveList(yqMjApprove, new YqMjApprove().getTableName());
    }

    @Override
    public YqMjApprove getYqMjApproveByInstanceId(String instanceId) {
        return yqMjApproveMapper.selectYqMjApproveByInstanceId("'" + instanceId + "'", new YqMjApprove().getTableName());
    }

    /**
     * 修改档案信息
     *
     * @param ids        主键id
     * @param categoryId 档案门类id
     * @param type       类型  0 件 1 卷 3 项目
     * @param mjstart    密级状态
     * @return
     */
    public int updateData(String ids, String categoryId, String type, String mjstart) {
        //获取当前登录用户信息
        String tenantCode = SecurityUtils.getLoginUser().getUser().getTenantCode();
        //查询门类信息
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(categoryId),
                tenantCode + Constants.BIG_TABLE_NAME);
        StringBuilder whereCondition = new StringBuilder();
        //拼接id
        if (StringUtils.isNotEmpty(ids)) {
            String[] idArr = ids.split(",");
            if (idArr.length > 1) whereCondition.append("  in (" + ids + ") ");
            else whereCondition.append(" = ").append(ids);
        }
        StringBuilder sqlSubtable = new StringBuilder();
        String tableName = "";
        String tableNameGeneral = tenantCode;
        String id = "";
        //组件信息
        if (type.equals("0")) {
            //表名
            tableName = tenantCategory.getFileTableName();
            //总表
            tableNameGeneral = tableNameGeneral + Constants.BIG_TABLE_YQDA;
            id = " DA_ID  ";
        }
        //组卷
        if (type.equals("1")) {
            //表名
            tableName = tenantCategory.getFolderTableName();
            //总表
            tableNameGeneral = tableNameGeneral + Constants.BIG_TABLE_YQFOLDER;
            String tableNameFile = tenantCategory.getFileTableName();
            id = " FOLDER_ID  ";
            //处理关联表sql
            sqlSubtable.append(" update " + tableNameFile + " file ");
            sqlSubtable.append("  set file.MJ = '" + mjstart + "' ");
            sqlSubtable.append(" where file.ID in ( ");
            sqlSubtable.append(" SELECT ff.DA_ID FROM " + tenantCode + Constants.BIG_TABLE_FOLDER_NAME + " ff WHERE  ff.FOLDER_ID ");
            sqlSubtable.append(whereCondition);
            sqlSubtable.append(" )");
        }
        StringBuilder sql = new StringBuilder();
        StringBuilder sqlSumTable = new StringBuilder().append(" update " + tableNameGeneral);
        StringBuilder sqlTable = new StringBuilder().append(" update " + tableName);
        sql.append(" set MJ = '" + mjstart + "' ");
        sqlTable.append(sql).append(" where ID " + whereCondition);
        sqlSumTable.append(sql).append(" where  " + id + whereCondition);
        if (!type.equals("3")) {
            mjIdentifyMapper.updateTableData(sqlTable.toString());
            mjIdentifyMapper.updateTableData(sqlSumTable.toString());
        }
        if (sqlSubtable.toString() != null && !"".equals(sqlSubtable.toString())) {
            mjIdentifyMapper.updateTableData(sqlSubtable.toString());
        }
        return 1;
    }


    /**
     * 处理排序
     *
     * @param seqencing
     * @return
     */
    public String handlSeqencing(String seqencing, String s) {
        String dataOrder = "";
        if (!"".equals(seqencing) && seqencing != null) {
            String[] strArray = seqencing.split(",");
            dataOrder += " order by ";
            for (int i = 0; i < strArray.length; i++) {
                String arr = strArray[i];
                String[] result1 = arr.split("\\$", -1);
                ;
                String filename = result1[1];
                if ("asc".equals(filename)) {
                    if (i == 0) {
                        dataOrder += s + result1[0] + " asc";
                    } else {
                        dataOrder += "," + s + result1[0] + " asc";
                    }
                } else if ("desc".equals(filename)) {
                    if (i == 0) {
                        dataOrder += s + result1[0] + " desc";
                    } else {
                        dataOrder += "," + s + result1[0] + " desc";
                    }
                }
            }
        }
        return dataOrder;
    }

    //拼接前端查询条件
    public void concatQueryCondition(JSONArray searchCondition, StringBuilder queryCondition, String montage) {
        //拼接前端查询条件
        if (searchCondition != null && searchCondition.size() > 0) {
            String queryType = null;        //查询类型
            String showType = null;        //展示类型
            String fieldName = null;        //展示类型
            String[] queryValue = new String[2];        //查询值
            for (int j = 0; j < searchCondition.size(); j++) {
                JSONObject jsonObject = searchCondition.getJSONObject(j);
                queryType = jsonObject.getString("queryType"); //根据查询项获取对应的查询类型
                showType = jsonObject.getString("showType"); //根据查询项获取对应的展示类型
                fieldName = montage + jsonObject.getString("column");
                if ("4".equals(queryType)) {    //区间查询会有2个值
                    queryValue[0] = jsonObject.getString("value");        //根据查询项获取对应的查询值
                    queryValue[1] = jsonObject.getString("valueTwo");
                } else {
                    queryValue[0] = jsonObject.getString("value");        //根据查询项获取对应的查询值
                }
                //logger.debug("queryColumns["+j+"] = "+queryColumns[j]+"--"+queryValue[0]);
                if (org.apache.commons.lang3.StringUtils.isNotBlank(queryValue[0])) {
                    queryCondition.append(getQueryCriteriaByType(fieldName, showType, queryType, queryValue));
                }
            }
        }
    }

    /**
     * <p>Title: getQueryCriteriaByType</p>
     * <p>Description: 根据传入的类型type 组合查询条件</p>
     *
     * @param column   列名
     * @param showType 查询类型
     *                 0	不参加查询	暂不考虑;
     *                 1	精确查询		= '匹配值';
     *                 2	模糊查询		like '%匹配值%';
     *                 3	左匹配查询	like '匹配值%';
     *                 4	区间查询		'匹配值1'<列<'匹配值2'	?是否包含=;
     *                 5	列表查询		不做处理;
     *                 6	单选对话框	不做处理;
     *                 7	多选对话框	不做处理;
     *                 8	多词检索		分词 以空格为标志;
     * @param values   查询值
     * @return
     */
    public String getQueryCriteriaByType(String column, String showType, String queryType, String[] values) {
        String criteria = " ";
        Integer type = Integer.parseInt(queryType);
        switch (type) {
            case 0: //不参加查询	暂不考虑;
                criteria = " ";
                break;
            case 1: //精确查询	= '匹配值';
                criteria += column + " = '" + values[0] + "' and";
                break;
            case 2: //模糊查询	like '%匹配值%';
                criteria += column + " like '%" + values[0] + "%' and";
                break;
            case 3: //左匹配查询	like '匹配值%';
                criteria += column + " like '" + values[0] + "%' and";
                break;
            case 4: //区间查询	'匹配值1'<=列<='匹配值2'
                if (StringUtils.isNotEmpty(values[0])) {
                    criteria += "'" + values[0] + "' <= " + column + " and";
                }
                if (StringUtils.isNotEmpty(values[1])) {
                    criteria += " " + column + " <= '" + values[1] + "' and";
                }
                break;
            case 5: //列表查询	不做处理;
                criteria = " ";
                break;
            case 6: //单选对话框	不做处理;
                criteria = " ";
                break;
            case 7: //多选对话框	不做处理;
                criteria = " ";
                break;
            case 8: //多词检索	分词 以空格为标志;	多词检索中 如果有查询列里的值存在空格 怎么处理 (查询时使用""将带空格需要整体查询的值标记 , 例如:"A B")
                String[] value = values[0].split(" ");
                criteria += "(";
                for (int i = 0; i < value.length; i++) {
                    if (i == 0) {
                        criteria += column + " like '%" + value[i] + "%'";
                    } else {
                        criteria += " or " + column + " like '%" + value[i] + "%'";
                    }
                }
                criteria += ") and";
                break;
            default:
                break;
        }
        return criteria;
    }

    /**
     * 密级判断
     *
     * @param yqMjApprove
     * @return
     */
    public int determineMjType(YqMjApprove yqMjApprove) {
        //获取当前登录用户信息
        String tenantCode = SecurityUtils.getLoginUser().getUser().getTenantCode();
        //查询门类信息
        TenantCategory tenantCategory = tenantCategoryMapper.selectTenantCategoryByID(Long.valueOf(yqMjApprove.getCategoryId()),
                tenantCode + Constants.BIG_TABLE_NAME);
        Integer type = Integer.parseInt(yqMjApprove.getType());
        StringBuilder sqlSubtable = new StringBuilder();
        //件
        if (type == 0) {
            if (tenantCategory.getType() != 0) {
                String tableName = tenantCategory.getFolderTableName();
                //处理关联表sql
                sqlSubtable.append(" select  file.ID,IFNULL( file.MJ,'-1') AS MJ from " + tableName + " file ");
                sqlSubtable.append(" where file.ID in ( ");
                sqlSubtable.append(" SELECT ff.FOLDER_ID FROM " + tenantCode + Constants.BIG_TABLE_FOLDER_NAME + " ff WHERE  ff.DA_ID = ");
                sqlSubtable.append(yqMjApprove.getFilesId());
                sqlSubtable.append(" )");
            }
        }
        //组卷
        if (type == 1) {
            String tableNameFile = tenantCategory.getFileTableName();
            //处理关联表sql
            sqlSubtable.append(" select file.ID,IFNULL( file.MJ,'-1') AS MJ from " + tableNameFile + " file ");
            sqlSubtable.append(" where file.ID in ( ");
            sqlSubtable.append(" SELECT ff.DA_ID FROM " + tenantCode + Constants.BIG_TABLE_FOLDER_NAME + " ff WHERE  ff.FOLDER_ID = ");
            sqlSubtable.append(yqMjApprove.getFilesId());
            sqlSubtable.append(" )");
        }
        int max = -1;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(sqlSubtable.toString())) {
            List<Map<String, Object>> mapList = mjIdentifyMapper.selectUnionALLTableData(" t.ID,t.MJ ", sqlSubtable.toString());
            if (null != mapList && mapList.size() > 0) {
                max = mapList.stream().collect(Collectors.summarizingInt(c -> Integer.parseInt(c.get("MJ").toString()))).getMax();
            }
        }
        return max;
    }

}
